import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { ElMessage } from 'element-plus'
import Dashboard from '@/views/Dashboard.vue'
import EntityView from '@/views/EntityView.vue'
<#if enableSecurity>
import LoginView from '@/views/LoginView.vue'
import { useAuthStore } from '@/stores/auth'
</#if>
import { entities } from '@/config/entities'

const routes: RouteRecordRaw[] = [
<#if enableSecurity>
  {
    path: '/login',
    name: 'Login',
    component: LoginView,
    meta: {
      requiresAuth: false,
      title: '登录'
    }
  },
</#if>
  {
    path: '/',
    name: 'Dashboard',
    component: Dashboard,
    meta: {
      requiresAuth: ${enableSecurity?string("true", "false")},
      title: '首页'
    }
  },
  {
    path: '/entity/:tableName',
    name: 'EntityView',
    component: EntityView,
    meta: {
      requiresAuth: ${enableSecurity?string("true", "false")},
      title: '实体管理'
    },
    beforeEnter: (to) => {
      const tableName = to.params.tableName as string
      const entityExists = entities.some(entity => entity.tableName === tableName)

      if (!entityExists) {
        ElMessage.warning(`未找到表 ${tableName} 的配置`)
        return { name: 'Dashboard' }
      }
    }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/'
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior() {
    return { top: 0 }
  }
})

router.beforeEach((to, from, next) => {
<#if enableSecurity>
  const authStore = useAuthStore()
  const requiresAuth = to.meta.requiresAuth !== false

  if (requiresAuth && !authStore.isAuthenticated) {
    return next({
      name: 'Login',
      query: { redirect: to.fullPath }
    })
  }

  if (to.name === 'Login' && authStore.isAuthenticated) {
    return next({ name: 'Dashboard' })
  }

  if (typeof to.meta.title === 'string') {
    document.title = `${to.meta.title} - 通用管理系统`
  } else {
    document.title = '通用管理系统'
  }

  next()
<#else>
  if (typeof to.meta.title === 'string') {
    document.title = `${to.meta.title} - 通用管理系统`
  } else {
    document.title = '通用管理系统'
  }
  next()
</#if>
})

export default router
